package edu.zjut.hjg.saas.biz.support;

import java.util.List;

/**
 * 分页类
 * 
 * @author hjg
 */
public class Paginated<T> {
    private int     pageSize  = 20;
    private int     totalSize = 0;
    private int     start     = 0;
    private List<T> values;

    public boolean hasPrePage() {
        return start >= pageSize;
    }

    public boolean hasNextPage() {
        return start + pageSize < totalSize;
    }

    public int getNextPage() {
        return hasNextPage() ? getCurrPage() + 1 : getCurrPage();
    }

    public int getPrePage() {
        return hasPrePage() ? getCurrPage() - 1 : getCurrPage();
    }

    public void copyPaginatedInfo(Paginated<?> paginated) {
        this.pageSize = paginated.getPageSize();
        this.totalSize = paginated.getTotalSize();
        this.start = paginated.getStart();
    }

    public int getTotalPage() {
        int left = totalSize % pageSize == 0 ? 0 : 1;
        return totalSize / pageSize + left;
    }

    /**
     * @return 当前页，从1开始
     */
    public int getCurrPage() {
        if (getTotalPage() == 0) {
            return 0;
        }
        int left = start % pageSize == 0 ? 1 : 2;
        return start / pageSize + left;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        if (pageSize <= 0) {
            throw new RuntimeException("pageSize must be greater than 0");
        }
        this.pageSize = pageSize;
    }

    public int getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(int totalSize) {
        this.totalSize = totalSize;
    }

    public List<T> getValues() {
        return values;
    }

    public void setValues(List<T> values) {
        this.values = values;
    }

    @Override
    public String toString() {
        return "Paginated [pageSize=" + pageSize + ", start=" + start + ", totalSize=" + totalSize
                + ", values=" + values + "]";
    }
}
